package com.newtouch.bxzs.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.em.CustomerTagEnum;
import com.newtouch.bxzs.common.base.em.DistributionTypeEnum;
import com.newtouch.bxzs.common.base.em.SystemParamsEnum;
import com.newtouch.bxzs.common.base.model.PersonalCustomer;
import com.newtouch.bxzs.common.base.model.PersonalCustomerGroupMap;
import com.newtouch.bxzs.common.base.util.*;
import com.newtouch.bxzs.enterprise.controller.PersonalCustomerController;
import com.newtouch.bxzs.enterprise.mapper.PersonalCustomerGroupMapMapper;
import com.newtouch.bxzs.enterprise.mapper.PersonalCustomerMapper;
import com.newtouch.bxzs.enterprise.model.bo.BankCustomerAnalysisBO;
import com.newtouch.bxzs.enterprise.model.bo.CustomerBO;
import com.newtouch.bxzs.enterprise.model.bo.InsuranceCustomerAnalysisBO;
import com.newtouch.bxzs.enterprise.model.bo.PersonalCustomerBO;
import com.newtouch.bxzs.enterprise.model.vo.CustomerAnalysisVO;
import com.newtouch.bxzs.enterprise.model.vo.CustomerVO;
import com.newtouch.bxzs.enterprise.model.vo.PersonalCustomerVO;
import com.newtouch.bxzs.enterprise.service.PersonalCustomerService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 个人客户业务实现层
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2020/12/22 10:39</td>
 * <td>lingshouyi</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author lingshouyi
 * @version 1.0.0
 * @since 1.0.0
 */

@Service
public class PersonalCustomerServiceImpl implements PersonalCustomerService {

    @Autowired
    private PersonalCustomerMapper personalCustomerMapper;

    @Autowired
    private PersonalCustomerGroupMapMapper personalCustomerGroupMapMapper;

    @Autowired
    RedisUtils redisUtils;

    /**
     * 静态变量：系统日志
     */
    private static final Log logger = LogFactory.getLog(PersonalCustomerController.class);

    @Override
    public CustomerBO getCustomerList(CustomerVO customerVO) {
        CustomerBO customerBO = new CustomerBO();
        List<PersonalCustomer> personalCustomerList = personalCustomerMapper.getCustomerList(StringUtils.isEmpty(customerVO.getCustomerName()) ? null : customerVO.getCustomerName(), StringUtils.isEmpty(customerVO.getGroupId()) ? null : customerVO.getGroupId(), Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserJobNumber());
        /*当查询客户集合为空时*/
        if (CollectionUtils.isEmpty(personalCustomerList)) {
            /*返回空集合*/
            customerBO.setList(Collections.emptyList());
            customerBO.setCount(0);
            return customerBO;
        }
        customerBO.setList(EntityToBeanUtils.copyBean(personalCustomerList, PersonalCustomerBO.class));
        /*客户人数*/
        customerBO.setCount(personalCustomerList.size());
        return customerBO;
    }

    @Override
    public PersonalCustomerBO getPersonalCustomerDetail(String customerId) {
        if (StringUtils.isEmpty(customerId)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        /*根据客户ID获取当前客户详情*/
        PersonalCustomer personalCustomer = personalCustomerMapper.selectById(customerId);
        if (personalCustomer == null) {
            return null;
        }
        PersonalCustomerBO personalCustomerBO = new PersonalCustomerBO();
        BeanUtils.copyProperties(personalCustomer, personalCustomerBO);
        List<PersonalCustomerGroupMap> groupMap = personalCustomerGroupMapMapper.selectList(new QueryWrapper<PersonalCustomerGroupMap>().eq("CUSTOMER_ID", customerId));
        /*群组Id 集合*/
        List<String> groupsList = new ArrayList<>();
        /*将遍历的群组id添加到groupsList*/
        for (PersonalCustomerGroupMap personalCustomerGroupMap : groupMap) {
            groupsList.add(personalCustomerGroupMap.getGroupId());
        }
        /*返回群组Ids*/
        personalCustomerBO.setGroupIds(groupsList);
        return personalCustomerBO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String modifyPersonalCustomer(PersonalCustomerVO personalCustomerVO) {
        /*personalCustomerVO是否为空*/
        if (BeanUtil.isEmpty(personalCustomerVO)) {
            return null;
        }
        PersonalCustomer customer = new PersonalCustomer();
        BeanUtil.copyProperties(personalCustomerVO, customer);
        /*校验必填项,证件,手机号*/
        checkCustomer(customer);
        /*判断客户ID是否为空，为空新增，不为空修改*/
        if (StringUtils.isEmpty(customer.getCustomerId())) {
            /*获取当前用户下的所有个人客户*/
            List<PersonalCustomer> customerList = personalCustomerMapper.selectList(
                    new QueryWrapper<PersonalCustomer>()
                            .eq("CUSTOMER_CERTIFICATE_TYPE", customer.getCustomerCertificateType()).
                            eq("CUSTOMER_CERTIFICATE_NUMBER", customer.getCustomerCertificateNumber()).
                            eq("CUSTOMER_NAME", customer.getCustomerName()));
            if (!CollectionUtils.isEmpty(customerList)) {
                throw new BaseException(BaseErrorEnum.DATA_EXISTS);
            }
            /*客户标识 -->自建客户*/
            customer.setCustomerLabel(CustomerTagEnum.SELF_BUILT.getCode()); //客户标识: 1,存 2,建 3,分 4,接
            /*设置客户的拼音*/
            customer.setCustomerNameFullSpelling(PinYinUtils.toPinyin(customer.getCustomerName()).replaceAll("[^a-z^A-Z]", ""));
            /*设置创建人ID*/
            customer.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            /*创建时间*/
            customer.setCreateTime(new Date());
            /*设置修改人ID*/
            customer.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            /*设置修改时间*/
            customer.setUpdateTime(new Date());
            /*设置所属用户*/
            customer.setUserJobNumber(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserJobNumber());
            /*插入新增客户*/
            personalCustomerMapper.insert(customer);
            logger.info("成功增加个人客户信息");
        } else {
            /*修改自建客户*/
            /*获取当前客户信息*/
            PersonalCustomer personalCustomer = personalCustomerMapper.selectById(customer.getCustomerId());
            if (StringUtils.isEmpty(personalCustomer)) {
                return null;
            }
            /*获取当前客户标识集合*/
            List<String> tagList = Arrays.asList(personalCustomer.getCustomerLabel().split(","));
            /*判断是否为自建客户,是自建客户才可修改*/
            if (tagList.contains(CustomerTagEnum.SELF_BUILT.getCode())) {
                /*设置修改人,修改时间*/
                customer.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
                customer.setUpdateTime(new Date());
                /*拼音*/
                customer.setCustomerNameFullSpelling(PinYinUtils.toFirstChar(customer.getCustomerName()).replaceAll("[^a-z^A-Z]", ""));
                /*判断是否为存量客户*/
                if (tagList.contains(CustomerTagEnum.STOCK.getCode())) {
                    /*存量客户三要素不可修改*/
                    if (!customer.getCustomerName().equals(personalCustomer.getCustomerName())
                            || !customer.getCustomerCertificateType().equals(personalCustomer.getCustomerCertificateType())
                            || !customer.getCustomerCertificateNumber().equals(personalCustomer.getCustomerCertificateNumber())) {
                        throw new BaseException(BaseErrorEnum.FIELD_CANNOT_MODIFY);
                    }
                }
                logger.info("成功修改个人客户信息");
                personalCustomerMapper.updateById(customer);
            }
        }
        return this.updateCustomerGroup(customer.getCustomerId(), personalCustomerVO.getGroupIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deletePersonalCustomer(List<String> customerIds) {
        /*判断客户ID集合是否为空*/
        if (CollectionUtils.isEmpty(customerIds)) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
        /*判断ID集合是否存在空字符串,如果有就移除.*/
        customerIds.removeIf(StringUtils::isEmpty);
        /*只有自建客户才可删除*/
        QueryWrapper<PersonalCustomer> qw = new QueryWrapper<>();
        qw.in("CUSTOMER_ID", customerIds).eq("CUSTOMER_LABEL", CustomerTagEnum.SELF_BUILT.getCode());
        List<PersonalCustomer> customers = personalCustomerMapper.selectList(qw);
        if (customers != null && customers.size() == customerIds.size()) {
            /*删除客户成功后再删除客户分组关联表的数据*/
            if (personalCustomerMapper.deleteBatchIds(customerIds) == 1) {
                /*删除客户分组关联表的数据*/
                personalCustomerGroupMapMapper.delete(new QueryWrapper<PersonalCustomerGroupMap>().in("CUSTOMER_ID", customerIds));
            }
        } else {
            throw new BaseException(BaseErrorEnum.CANNOT_MODIFY);
        }
        return "删除成功";
    }

    @Override
    public InsuranceCustomerAnalysisBO getInsuranceCustomerAnalysisInformation(CustomerAnalysisVO customerAnalysisVO) {
        /*验证必传参数*/
        checkCustomerAnalysis(customerAnalysisVO);
        customerAnalysisVO.setCustomerBehaviorDataQueryMonth(redisUtils.get(SystemParamsEnum.CUSTOMER_BEHAVIOR_DATA_QUERY_MONTH.getCode()));
        SendHttpRequestUtils<CustomerAnalysisVO> sendHttpRequestUtils = new SendHttpRequestUtils<>();
        String noticeType = redisUtils.get(SystemParamsEnum.BANKING_OR_INSURANCE.getCode());
        if (noticeType.equals(DistributionTypeEnum.BANK.getCode())) {
            JSONObject response = sendHttpRequestUtils.sendHttpRequestToJson(customerAnalysisVO, redisUtils.get(SystemParamsEnum.BANK_TO_INSURANCE_CUSTOMER_ANALYSIS_INFO.getCode()));
            Object data = response.get("data");
            if(!StringUtils.isEmpty(data)){
                return JSONObject.toJavaObject(JSONObject.parseObject(JSONUtil.toJsonStr(data)),InsuranceCustomerAnalysisBO.class);
            }
        }
        if (noticeType.equals(DistributionTypeEnum.INSURANCE.getCode())){
            JSONObject jsonObject = sendHttpRequestUtils.sendHttpRequestToJson(customerAnalysisVO, redisUtils.get(SystemParamsEnum.INSURANCE_CUSTOMER_ANALYSIS_INFO.getCode()));
            if(jsonObject != null) {
                return JSONObject.toJavaObject(jsonObject, InsuranceCustomerAnalysisBO.class);
            }
        }
        logger.error("暂无该客户分析信息");
        throw new BaseException(BaseErrorEnum.NO_CUSTOMER_ANALYSIS_INFORMATION);
    }

    /**
     * 验证客户分析信息传入参数
     *
     * @param customerAnalysisVO 客户分析信息查询VO
     */
    private void checkCustomerAnalysis(CustomerAnalysisVO customerAnalysisVO) {
        if(StringUtils.isEmpty(customerAnalysisVO) || StringUtils.isEmpty(customerAnalysisVO.getCustomerName()) || StringUtils.isEmpty(customerAnalysisVO.getCustomerCertificateType()) || StringUtils.isEmpty(customerAnalysisVO.getCustomerCertificateNumber())){
            logger.error("必填项未填写！");
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }
    }

    @Override
    public BankCustomerAnalysisBO getBankCustomerAnalysisInformation(CustomerAnalysisVO customerAnalysisVO) {
        /*验证必传参数*/
        checkCustomerAnalysis(customerAnalysisVO);
        customerAnalysisVO.setCustomerBehaviorDataQueryMonth(redisUtils.get(SystemParamsEnum.CUSTOMER_BEHAVIOR_DATA_QUERY_MONTH.getCode()));
        SendHttpRequestUtils<CustomerAnalysisVO> sendHttpRequestUtils = new SendHttpRequestUtils<>();
        String noticeType = redisUtils.get(SystemParamsEnum.BANKING_OR_INSURANCE.getCode());
        if (noticeType.equals(DistributionTypeEnum.INSURANCE.getCode())) {
            JSONObject response = sendHttpRequestUtils.sendHttpRequestToJson(customerAnalysisVO, redisUtils.get(SystemParamsEnum.INSURANCE_TO_BANK_CUSTOMER_ANALYSIS_INFO.getCode()));
            Object data = response.get("data");
            if(!StringUtils.isEmpty(data)){
                return JSONObject.toJavaObject(JSONObject.parseObject(JSONUtil.toJsonStr(data)),BankCustomerAnalysisBO.class);
            }
        }
        if (noticeType.equals(DistributionTypeEnum.BANK.getCode())){
            JSONObject jsonObject = sendHttpRequestUtils.sendHttpRequestToJson(customerAnalysisVO, redisUtils.get(SystemParamsEnum.BANK_CUSTOMER_ANALYSIS_INFO.getCode()));
            if(jsonObject != null) {
                return JSONObject.toJavaObject(jsonObject, BankCustomerAnalysisBO.class);
            }
        }
        logger.error("暂无该客户分析信息");
        throw new BaseException(BaseErrorEnum.NO_CUSTOMER_ANALYSIS_INFORMATION);
    }

    private String updateCustomerGroup(String CustomerId, List<String> groupIds) {
        /*将用户批量插入分组*/
        /*查找该用户分别属于哪些组,并移除*/
        QueryWrapper<PersonalCustomerGroupMap> qw = new QueryWrapper<>();
        qw.eq("CUSTOMER_ID", CustomerId);
        personalCustomerGroupMapMapper.delete(qw);
        /*将客户重新添加组*/
        if (!CollectionUtils.isEmpty(groupIds)) {
            List<PersonalCustomerGroupMap> list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(groupIds)) {
                for (String groupId : groupIds) {
                    PersonalCustomerGroupMap item = new PersonalCustomerGroupMap();
                    item.setGroupId(groupId);
                    item.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
                    item.setCustomerId(CustomerId);
                    item.setCreateTime(new Date());
                    item.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
                    item.setUpdateTime(new Date());
                    list.add(item);
                }
                personalCustomerGroupMapMapper.insertBach(list);
            }
        }
        return null;
    }

    /**
     * 校验必填项,证件,手机号
     *
     * @param customer 客户
     */
    private void checkCustomer(PersonalCustomer customer) {
        /*校验必填项*/
        if (StringUtils.isEmpty(customer.getCustomerName()) ||
                StringUtils.isEmpty(customer.getCustomerPhone()) ||
                StringUtils.isEmpty(customer.getCustomerCertificateType()) ||
                StringUtils.isEmpty(customer.getCustomerCertificateNumber()) ||
                StringUtils.isEmpty(customer.getCustomerSex())) {
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }

        QueryWrapper<PersonalCustomer> qw = new QueryWrapper<>();
        qw.eq("CUSTOMER_CERTIFICATE_NUMBER", customer.getCustomerCertificateNumber());

        if (!StringUtils.isEmpty(customer.getCustomerId())) {
            qw.notIn("CUSTOMER_ID", customer.getCustomerId());
        }
        if (!CollectionUtils.isEmpty(personalCustomerMapper.selectList(qw))) {
            throw new BaseException(BaseErrorEnum.DATA_EXISTS);
        }
        /*校验证件*/
        CheckCertificateTypeUtil.checkCertificate(customer.getCustomerCertificateType(), customer.getCustomerCertificateNumber());
        /*验证手机号*/
        if (!Validator.isMobile(customer.getCustomerPhone())) {
            throw new BaseException(BaseErrorEnum.BODY_NOT_MATCH);
        }
    }
}
